<template>
  <div class="page-container">
    <h1 class="metro-title"><i class="metro-icon"></i>地铁线路管理</h1>
    <div id="mapView" class="map-view">
      <!-- 图层控制面板 -->
      <div class="layer-control-panel">
        <el-card class="layer-card">
          <el-collapse v-model="activeCollapse">
            <el-collapse-item title="图层显示控制" name="layers">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-checkbox
                  v-model="layerVisibility.subwayLine"
                  @change="toggleLayerVisibility('subwayLine')"
                  class="metro-checkbox"
                  >地铁线路</el-checkbox
                >
                <el-checkbox
                  v-model="layerVisibility.subwayStation"
                  @change="toggleLayerVisibility('subwayStation')"
                  class="metro-checkbox"
                  >地铁站点</el-checkbox
                >
              </el-space>
            </el-collapse-item>
            <el-collapse-item title="图层操作控制" name="operations">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-button type="primary" @click="startAddLine" :disabled="isDrawing" class="metro-button">
                  <el-icon><Plus /></el-icon> 新增地铁线路
                </el-button>
              </el-space>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </div>

      <!-- 线路属性表单对话框 -->
      <el-dialog
        v-model="lineFormVisible"
        :title="formMode === 'add' ? '新增地铁线路' : '编辑地铁线路'"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form :model="lineForm" label-width="120px" :rules="lineFormRules" ref="lineFormRef">
          <el-form-item label="线路名称" prop="LineName">
            <el-input v-model="lineForm.LineName" placeholder="请输入线路名称"></el-input>
          </el-form-item>
          <el-form-item label="线路编号" prop="LineNumber">
            <el-input v-model="lineForm.LineNumber" placeholder="请输入线路编号"></el-input>
          </el-form-item>
          <el-form-item label="站点数量" prop="StationCount">
            <el-input-number
              v-model="lineForm.StationCount"
              :min="1"
              :max="50"
              placeholder="请输入站点数量"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="首班车时间" prop="FirstTrainTime">
            <el-input
              v-model="lineForm.FirstTrainTime"
              placeholder="请输入首班车时间 (格式: HH:mm)"
            ></el-input>
          </el-form-item>
          <el-form-item label="末班车时间" prop="LastTrainTime">
            <el-input
              v-model="lineForm.LastTrainTime"
              placeholder="请输入末班车时间 (格式: HH:mm)"
            ></el-input>
          </el-form-item>
          <el-form-item label="轨道类型" prop="TrackType">
            <el-select v-model="lineForm.TrackType" placeholder="请选择轨道类型" style="width: 100%">
              <el-option label="地下" value="地下"></el-option>
              <el-option label="高架" value="高架"></el-option>
              <el-option label="混合" value="混合"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日均客流量" prop="DailyPassengers">
            <el-input-number
              v-model="lineForm.DailyPassengers"
              :min="0"
              :step="1000"
              placeholder="请输入日均客流量"
            ></el-input-number>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelLineForm">取消</el-button>
            <el-button type="primary" @click="submitLineForm">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 线路属性查看对话框 -->
      <el-dialog v-model="lineInfoVisible" title="地铁线路信息" width="500px" :key="refreshLineKey">
        <div v-if="selectedLine">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="线路名称">{{
              selectedLine.attributes.LineName
            }}</el-descriptions-item>
            <el-descriptions-item label="线路编号">{{
              selectedLine.attributes.LineNumber
            }}</el-descriptions-item>
            <el-descriptions-item label="站点数量">{{
              selectedLine.attributes.StationCount
            }}</el-descriptions-item>
            <el-descriptions-item label="首班车时间">{{
              selectedLine.attributes.FirstTrainTime
            }}</el-descriptions-item>
            <el-descriptions-item label="末班车时间">{{
              selectedLine.attributes.LastTrainTime
            }}</el-descriptions-item>
            <el-descriptions-item label="轨道类型">{{
              selectedLine.attributes.TrackType
            }}</el-descriptions-item>
            <el-descriptions-item label="日均客流量">{{
              selectedLine.attributes.DailyPassengers
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="lineInfoVisible = false">关闭</el-button>
            <el-button type="primary" @click="editLine">编辑</el-button>
            <el-button type="danger" @click="confirmDeleteLine">删除</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 删除确认对话框 -->
      <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px">
        <p>确定要删除该地铁线路吗？此操作不可恢复。</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteConfirmVisible = false">取消</el-button>
            <el-button type="danger" @click="deleteLine">确定删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../../utils/GaoDeBaseLayer'

type LineFormType = {
  LineName: string
  LineNumber: string
  StationCount: number
  FirstTrainTime: string
  LastTrainTime: string
  TrackType: string
  DailyPassengers: number
}

let view: MapView | null = null
let subwayLineLayer: FeatureLayer | null = null
let subwayStationLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let tempGraphic: Graphic | null = null

// 图层可见性控制
const layerVisibility = ref({
  subwayLine: true,
  subwayStation: true,
})

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'operations'])
// 添加一个刷新标记
const refreshLineKey = ref(0)

// 表单相关
const lineFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const lineFormVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')
const isDrawing = ref(false)
const lineInfoVisible = ref(false)
const deleteConfirmVisible = ref(false)
let selectedLine: Graphic | null = null

// 线路表单数据
const lineForm = reactive<LineFormType>({
  LineName: '',
  LineNumber: '',
  StationCount: 1,
  FirstTrainTime: '',
  LastTrainTime: '',
  TrackType: '地下',
  DailyPassengers: 0,
})

// 线路表单验证规则
const lineFormRules = {
  LineName: [{ required: true, message: '请输入线路名称', trigger: 'blur' }],
  LineNumber: [{ required: true, message: '请输入线路编号', trigger: 'blur' }],
  StationCount: [{ required: true, message: '请输入站点数量', trigger: 'blur' }],
  FirstTrainTime: [{ required: true, message: '请选择首班车时间', trigger: 'blur' }],
  LastTrainTime: [{ required: true, message: '请选择末班车时间', trigger: 'blur' }],
  TrackType: [{ required: true, message: '请选择轨道类型', trigger: 'blur' }],
  DailyPassengers: [{ required: true, message: '请输入日均客流量', trigger: 'blur' }],
}

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  switch (layerType) {
    case 'subwayLine':
      if (subwayLineLayer) {
        subwayLineLayer.visible = Boolean(layerVisibility.value.subwayLine)
      }
      break
    case 'subwayStation':
      if (subwayStationLayer) {
        subwayStationLayer.visible = Boolean(layerVisibility.value.subwayStation)
      }
      break
  }
}

// 开始添加地铁线路
const startAddLine = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上绘制地铁线路')

  // 开始绘制线
  sketchViewModel.create('polyline')
}

// 取消线路表单
const cancelLineForm = () => {
  lineFormVisible.value = false
  resetLineForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }
}

// 重置线路表单
const resetLineForm = () => {
  if (lineFormRef.value) {
    lineFormRef.value.resetFields()
  }

  lineForm.LineName = ''
  lineForm.LineNumber = ''
  lineForm.StationCount = 1
  lineForm.FirstTrainTime = ''
  lineForm.LastTrainTime = ''
  lineForm.TrackType = '地下'
  lineForm.DailyPassengers = 0
}

// 提交线路表单
const submitLineForm = async () => {
  if (!lineFormRef.value) return

  await lineFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新线路
        addLine()
      } else {
        // 更新线路
        updateLine()
      }
    }
  })
}

// 添加新线路
const addLine = () => {
  if (!tempGraphic || !subwayLineLayer) return

  // 创建新的线路图形
  const attributes = {
    LineName: lineForm.LineName,
    LineNumber: lineForm.LineNumber,
    StationCount: lineForm.StationCount,
    FirstTrainTime: lineForm.FirstTrainTime,
    LastTrainTime: lineForm.LastTrainTime,
    TrackType: lineForm.TrackType,
    DailyPassengers: lineForm.DailyPassengers,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  subwayLineLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('地铁线路添加成功')
        lineFormVisible.value = false
        resetLineForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }
      } else {
        ElMessage.error('地铁线路添加失败')
      }
    })
    .catch((error) => {
      console.error('添加地铁线路出错:', error)
      ElMessage.error('地铁线路添加失败')
    })
}

// 编辑线路
const editLine = () => {
  if (!selectedLine) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedLine.attributes
  lineForm.LineName = attrs.LineName || ''
  lineForm.LineNumber = attrs.LineNumber || ''
  lineForm.StationCount = attrs.StationCount || 1
  lineForm.FirstTrainTime = attrs.FirstTrainTime || ''
  lineForm.LastTrainTime = attrs.LastTrainTime || ''
  lineForm.TrackType = attrs.TrackType || '地下'
  lineForm.DailyPassengers = attrs.DailyPassengers || 0

  lineInfoVisible.value = false
  lineFormVisible.value = true
}

// 更新线路
const updateLine = () => {
  if (!selectedLine || !subwayLineLayer) return

  // 更新属性
  const updatedGraphic = selectedLine.clone()
  updatedGraphic.attributes.LineName = lineForm.LineName
  updatedGraphic.attributes.LineNumber = lineForm.LineNumber
  updatedGraphic.attributes.StationCount = lineForm.StationCount
  updatedGraphic.attributes.FirstTrainTime = lineForm.FirstTrainTime
  updatedGraphic.attributes.LastTrainTime = lineForm.LastTrainTime
  updatedGraphic.attributes.TrackType = lineForm.TrackType
  updatedGraphic.attributes.DailyPassengers = lineForm.DailyPassengers

  // 应用编辑
  subwayLineLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('地铁线路更新成功')
        lineFormVisible.value = false
        resetLineForm()
        // 强制刷新组件
        nextTick(() => {
          refreshLineKey.value++
        })
      } else {
        ElMessage.error('地铁线路更新失败')
      }
    })
    .catch((error) => {
      console.error('更新地铁线路出错:', error)
      ElMessage.error('地铁线路更新失败')
    })
}

// 确认删除线路
const confirmDeleteLine = () => {
  lineInfoVisible.value = false
  deleteConfirmVisible.value = true
}

// 删除线路
const deleteLine = () => {
  if (!selectedLine || !subwayLineLayer) return

  subwayLineLayer
    .applyEdits({
      deleteFeatures: [selectedLine],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('地铁线路删除成功')
        deleteConfirmVisible.value = false
      } else {
        ElMessage.error('地铁线路删除失败')
      }
    })
    .catch((error) => {
      console.error('删除地铁线路出错:', error)
      ElMessage.error('地铁线路删除失败')
    })
}

// 初始化地图
onMounted(() => {
  // 创建地铁线路图层
  subwayLineLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/1',
    title: '地铁线路',
    visible: Boolean(layerVisibility.value.subwayLine),
    outFields: ['*'], // 确保所有字段都可用
    popupEnabled: false, // 禁用默认弹出窗口，使用自定义弹窗
  })

  // 创建地铁站点图层
  subwayStationLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/0',
    title: '地铁站点',
    visible: Boolean(layerVisibility.value.subwayStation),
    outFields: ['*'],
    popupEnabled: false,
  })

  // 创建草图图层
  sketchLayer = new GraphicsLayer({
    title: '草图图层',
  })

  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [subwayLineLayer, subwayStationLayer, sketchLayer], // 添加图层到地图
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    zoom: 10,
    center: [116.397428, 39.90923], // 默认中心点（北京）
  })

  // 创建草图视图模型
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: sketchLayer,
    defaultCreateOptions: {
      mode: 'click',
    },
    polylineSymbol: new SimpleLineSymbol({
      color: [0, 0, 255, 0.8],
      width: 4,
    }),
  })

  // 监听草图创建完成事件
  sketchViewModel.on('create', (event) => {
    if (event.state === 'complete') {
      // 绘制完成
      isDrawing.value = false
      tempGraphic = event.graphic

      // 显示表单
      formMode.value = 'add'
      lineFormVisible.value = true
    }
  })

  // 监听点击事件，用于查询要素信息
  view.on('click', async function (event) {
    // 如果正在绘制，则不处理点击事件
    if (isDrawing.value) return

    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 1 // 增加点击容差
    query.units = 'kilometers'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 查询地铁线路图层
      if (subwayLineLayer && subwayLineLayer.visible) {
        const lineResult = await subwayLineLayer.queryFeatures(query)
        if (lineResult.features.length > 0) {
          // 找到线路，显示信息
          selectedLine = lineResult.features[0]
          lineInfoVisible.value = true
          nextTick(() => {
            refreshLineKey.value++
          })
          return
        }
      }
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.metro-title {
  margin-bottom: 20px;
  color: #0052cc;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 40px;
  letter-spacing: 1px;
}

.metro-title::before {
  content: "";
  position: absolute;
  left: 0;
  width: 30px;
  height: 30px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%230052cc"><path d="M17.5,3H6.5C5.12,3,4,4.12,4,5.5v11C4,17.88,5.12,19,6.5,19h11c1.38,0,2.5-1.12,2.5-2.5v-11C20,4.12,18.88,3,17.5,3z M6.5,5h11C17.78,5,18,5.22,18,5.5v4h-2.05C15.43,8.07,14.15,7,12.5,7h-1C9.91,7,8.5,8.41,8.5,10.15V12H6V5.5C6,5.22,6.22,5,6.5,5z M17.5,17h-11C6.22,17,6,16.78,6,16.5V14h2.5v1c0,0.55,0.45,1,1,1h5c0.55,0,1-0.45,1-1v-1H18v2.5C18,16.78,17.78,17,17.5,17z M12.75,14.5h-1.5v-1h1.5V14.5z M12.5,12.5c-0.83,0-1.5-0.67-1.5-1.5s0.67-1.5,1.5-1.5s1.5,0.67,1.5,1.5S13.33,12.5,12.5,12.5z"/></svg>');
  background-repeat: no-repeat;
  background-size: contain;
}

.map-view {
  width: 100%;
  height: 100%;
  position: relative;
  flex-grow: 1;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  width: 280px;
}

.layer-card {
  background-color: rgba(255, 255, 255, 0.92);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: none;
  overflow: hidden;
}

.layer-card :deep(.el-collapse) {
  border: none;
}

.layer-card :deep(.el-collapse-item__header) {
  font-weight: 600;
  color: #0052cc;
  background-color: rgba(240, 245, 255, 0.8);
  padding: 12px 16px;
  border-bottom: 2px solid #e6effd;
}

.layer-card :deep(.el-collapse-item__content) {
  padding: 16px;
}

.metro-checkbox :deep(.el-checkbox__label) {
  font-size: 15px;
  color: #333;
}

.metro-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #0052cc;
  border-color: #0052cc;
}

.metro-button {
  background-color: #0052cc;
  border-color: #0052cc;
  font-weight: 600;
  border-radius: 6px;
  padding: 10px 16px;
  transition: all 0.3s;
}

.metro-button:hover {
  background-color: #003d99;
  border-color: #003d99;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

.metro-button:active {
  transform: translateY(0);
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

:deep(.el-dialog__header) {
  background-color: #0052cc;
  color: white;
  padding: 16px 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-button--danger) {
  background-color: #f5222d;
  border-color: #f5222d;
}

:deep(.el-button--danger:hover) {
  background-color: #cf1322;
  border-color: #cf1322;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 8px;
}

/* 描述列表样式 */
:deep(.el-descriptions) {
  background-color: #f9fbff;
  border-radius: 8px;
}

:deep(.el-descriptions__label) {
  background-color: #f0f5ff;
  font-weight: 500;
}

:deep(.el-descriptions__content) {
  padding: 12px 16px;
}
</style>